#!/bin/bash
# 部署API网关服务 (端口1000)

set -e

echo "开始部署API网关服务..."

# 检查是否在项目根目录
if [ ! -d "1-gateway/02-api-gateway" ]; then
    echo "错误: 请在项目根目录执行此脚本"
    exit 1
fi

# 进入API网关目录
cd 1-gateway/02-api-gateway

# 安装依赖
echo "安装Python依赖..."
pip install -r requirements.txt

# 创建日志目录
mkdir -p ../shared/logs

# 停止旧服务 (如果存在)
echo "停止旧服务..."
pkill -f "gunicorn.*1000" || true
sleep 2

# 启动新服务
echo "启动API网关服务 (端口1000)..."
nohup gunicorn -w 2 -b 127.0.0.1:1000 \
    --access-logfile ../shared/logs/gateway-access.log \
    --error-logfile ../shared/logs/gateway-error.log \
    --timeout 300 \
    --daemon \
    app:app > ../shared/logs/gateway-startup.log 2>&1

# 等待服务启动
sleep 3

# 检查服务状态
if curl -s http://127.0.0.1:1000/api/v1/health > /dev/null; then
    echo "✅ API网关服务启动成功 (端口1000)"
else
    echo "❌ API网关服务启动失败"
    echo "查看日志: tail -f ../shared/logs/gateway-error.log"
    exit 1
fi

echo "API网关服务部署完成"
echo "访问地址: http://127.0.0.1:1000"
echo "日志位置: 1-gateway/shared/logs/"
